package dyyx.simplerpc;

import java.lang.reflect.Method;

import com.alibaba.fastjson.JSON;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


// io.netty.channel.ChannelPipelineException: dyyx.simplerpc.ServerHandler is not a @Sharable handler, so can't be added or removed multiple times.
@Sharable
public class ServerHandler extends SimpleChannelInboundHandler<RpcRequest> {
	 
   private final HelloService helloService = new HelloServiceImpl();
 
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest msg) {        
        System.out.println(ctx.channel()+",msg="+JSON.toJSONString(msg));       
    	RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setRequestId(msg.getRequestId());
        try {
            Object handler = handler(msg);
            rpcResponse.setResult(handler);
        } catch (Throwable throwable) {
            rpcResponse.setError(throwable.toString());
            // throwable.printStackTrace();
        }
        ctx.writeAndFlush(rpcResponse);
    }
 
  
    private Object handler(RpcRequest request) throws Exception {
        Class<?> clazz = Class.forName(request.getClassName());
        String methodName = request.getMethodName();
 
        Class<?>[] parameterTypes = request.getParameterTypes();
        Object[] parameters = request.getParameters();
 
        Method method = HelloService.class.getMethod(methodName, parameterTypes);
        return method.invoke(helloService, parameters);
        
    }
    
    /*
    @Override
    // @SuppressWarnings("deprecation")
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        // ctx.fireExceptionCaught(cause);
    	System.out.println("error,"+cause);
    	try {
    	    ctx.channel().close().get();
    	}catch(Throwable e) {
        	System.out.println("close error,"+e);
    	}  	
    }
    */
}

